package org.penguin.study.bk.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.user.entity.User;
import org.penguin.study.bk.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author chengyinghua
 */
@Tag(name = "用户控制器", description = "用户信息")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Operation(summary = "用户表-分页列表查询", description = "用户表-分页列表查询")
    @GetMapping(value = "/page")
    public Result<?> queryPageList(User user,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Page<User> page = new Page<>(pageNo, pageSize);
        IPage<User> userPageData = userService.page(page, queryWrapper);
        return Result.ok(userPageData);
    }

    @Operation(summary = "用户表-根据id查询用户", description = "用户表-根据id查询用户")
    @GetMapping(value = "/detail/{userId}")
    public Result<?> userDetail(@PathVariable("userId") String userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        } else {
            return Result.ok(user);
        }
    }

    /**
     * @return
     * @功能：新增
     */
    @Operation(summary = "用户表-新增用户", description = "用户表-新增用户")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<User> add(@RequestBody User user) {
        Result<User> result = new Result<>();
        try {
            user.setCreatedBy("admin");
            user.setCreatedTime(LocalDateTime.now());
            user.setPassword("12345678");
            userService.save(user);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }
}
